package example.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import example.common.FileUtils;
import example.common.Result;
import example.dto.DidAndSidDTO;
import example.dto.ResponseDepartmentDTO;
import example.dto.SecondmentInfoDTO;
import example.entity.Department;
import example.entity.Secondment;
import example.entity.SecondmentDistributeInfo;
import example.mapper.*;
import example.service.ISecondmentDistributeInfoService;
import example.vo.ResResponseVO;
import example.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SecondmentDistributeInfoServiceImpl implements ISecondmentDistributeInfoService {

    @Value("${file.secondment_upload_pdf_dir}")
    private String secondmentUploadDir;

    @Value("${file.secondment_response_dir}")
    private String secondmentResponseDir;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private SecondmentMapper secondmentMapper;

    @Resource
    private SecondmentDistributeInfoMapper secondmentDistributeInfoMapper;

    @Resource
    private SecondmentContentInfoMapper secondmentContentInfoMapper;

    @Override
    @Transactional
    public Result uploadPdfFile(List<MultipartFile> files, Long secondmentId) {
        if (files == null || files.isEmpty()) {
            return Result.fail("请上传文件！");
        }
        try {
            StringBuilder pdfNames = new StringBuilder();
            StringBuilder pdfPaths = new StringBuilder();
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue; // 跳过空文件
                }

                // 生成唯一的文件名
                String originalFilename = file.getOriginalFilename();
                String fileName = StringUtils.cleanPath(originalFilename);
                String filePath = secondmentUploadDir + "\\" + fileName;
                if (pdfNames.length() > 0) {
                    pdfNames.append(";");
                    pdfPaths.append(";");
                }
                pdfNames.append(fileName);
                pdfPaths.append(filePath);
                File dest = new File(filePath);
                dest.getParentFile().mkdirs();
                file.transferTo(dest);

            }

            // 更新数据库
            Secondment secondment = new Secondment();
            secondment.setId(secondmentId);
            secondment.setPdfName(pdfNames.toString());
            secondment.setPdfPath(pdfPaths.toString());
            secondmentMapper.savePdfInfoById(secondment);
            // 同时创建一个文件夹
            Secondment sc = secondmentMapper.getById(secondmentId);
            String secondmentName = sc.getSecondmentName();
            Date createTime = sc.getCreateTime();
            String pattern = "yyyy年MM月dd日";

            // 创建SimpleDateFormat对象并指定日期格式
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);

            // 调用format()方法进行日期格式化
            String formattedDate = sdf.format(createTime);

            String rName = formattedDate + " " + secondmentName;
            String rPath = secondmentResponseDir + "\\" + formattedDate + " " + secondmentName;
            File folder = new File(rPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            Secondment rSecondment = new Secondment();
            rSecondment.setId(secondmentId);
            rSecondment.setResponseZipName(rName);
            rSecondment.setResponseZipPath(rPath);
            secondmentMapper.saveResponseZipFile(rSecondment);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }

    @Override
    public Result uploadConfirmFile(MultipartFile file, Long secondmentId) {
        if (null == file) {
            return Result.fail("请上传文件！");
        }
        try {
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String filePath = secondmentUploadDir + "\\" + fileName;
            File newFile = new File(filePath);
            newFile.getParentFile().mkdirs();
            file.transferTo(newFile);

            Secondment secondment = new Secondment();
            secondment.setId(secondmentId);
            secondment.setConfirmName(fileName);
            secondment.setConfirmPath(filePath);
            secondmentMapper.saveConfirmPdfInfoById(secondment);
        } catch (Exception e) {
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }
    @Override
    public void downloadConfirm(Long secondmentId,Long departmentId, HttpServletResponse response) {
        SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
        secondmentDistributeInfo.setDepartmentId(departmentId);
        secondmentDistributeInfo.setSecondmentId(secondmentId);
        SecondmentDistributeInfo secondmentDistributeInfo2 = secondmentDistributeInfoMapper.getResFile(secondmentDistributeInfo);
        String confirmName = secondmentDistributeInfo2.getConfirmName();
        String confirmPath = secondmentDistributeInfo2.getConfirmPath();
        System.out.println(confirmName + " " + confirmPath);
        if (confirmName != null && confirmPath != null) {
        FileUtils.download(confirmName, confirmPath, response);}
    }
    @Override
    public Result checkNumOfSecondment(Long secondmentId, List<String> departmentNames) {
        String pdfName = secondmentMapper.getPdfNameById(secondmentId);
        if (pdfName == null) {
            return Result.fail("请先上传pdf文件！");
        }
        Map<String, Integer> secondNumberOfDepartment = new HashMap<String, Integer>();
        for (String departmentName : departmentNames) {
            Department department = departmentMapper.getDepartmentByName(departmentName);
            SecondmentInfoDTO secondmentInfoDTO = new SecondmentInfoDTO();
            secondmentInfoDTO.setSecondmentId(secondmentId);
            secondmentInfoDTO.setDepartmentName(departmentName);
            //查找该部门已借调的人数
            Integer secondmentNumberAlready = userInfoMapper.getSecondmentEd(departmentName);
            //查找该部门本次借调的人数
            Integer secondmentNumberYet = secondmentContentInfoMapper.countNumberOfDepartmentAndSecondment(secondmentInfoDTO);
            Integer secondmentNumberSum = secondmentNumberAlready + secondmentNumberYet;
            //如果是二级部门
//            if (department.getLevelId().equals(2L)) {
//                secondNumberOfDepartment.put(departmentName, secondNumberOfDepartment.getOrDefault(departmentName, 0) + secondmentNumberSum);
//            }
            //如果是三级部门
//            if (department.getLevelId().equals(3L)) {
                //找到该部门所属的二级部门,
//                Long pId = departmentMapper.getParentDepartmentIdByName(departmentName);
//                String pName = departmentMapper.getDepartmentNameById(pId);
//                secondNumberOfDepartment.put(pName, secondNumberOfDepartment.getOrDefault(pName, 0) + secondmentNumberSum);
//                //如果该三级部门也需要判断人数
//                if (department.getNumberLimit().equals(1)) {
                    secondNumberOfDepartment.put(departmentName, secondmentNumberSum);
//                }
//            }
        }
        List<String> departmentList = new ArrayList<String>();
        for (Map.Entry<String,Integer> secondNumber:secondNumberOfDepartment.entrySet()){
            //获取部门人数
            Integer employeeNumber = departmentMapper.getEmployeeNumber(secondNumber.getKey());
            Integer maxSecondmentNumber = (int) (1.0 * employeeNumber * 0.02);
            Integer secondmentNumber = secondNumber.getValue();
            if (secondmentNumber>maxSecondmentNumber){
                int res = secondmentNumber - maxSecondmentNumber;
                String responseWarn = secondNumber.getKey()+"最大借调人数"+maxSecondmentNumber+"人，超出"+res+"人";
                departmentList.add(responseWarn);
            }
        }
        return Result.ok(departmentList);
    }

    @Override
    public Result distributeCase(Long secondmentId, List<String> departmentNames) {
        String pdfName = secondmentMapper.getPdfNameById(secondmentId);
        if (pdfName == null) {
            return Result.fail("请先上传pdf文件！");
        }

        List<Long> departmentIds = new ArrayList<>();
        for (String departmentName : departmentNames) {
            Long departmentId = departmentMapper.getDepartmentIdByName(departmentName);
            departmentIds.add(departmentId);
        }
        try {
            for (Long departmentId : departmentIds) {
                SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
                secondmentDistributeInfo.setDepartmentId(departmentId);
                secondmentDistributeInfo.setSecondmentId(secondmentId);
                secondmentDistributeInfo.setResponseState("未上报");
                secondmentDistributeInfo.setConfirm("未处理");
                secondmentDistributeInfoMapper.save(secondmentDistributeInfo);
            }
            return Result.ok("发布借调事项成功！");
        } catch (Exception e) {
            return Result.fail("请不要重复分发！");
        }
    }

    @Override
    public Result uploadResponseFile(List<MultipartFile> files, Long departmentId, Long secondmentId) {
        if (files == null || files.isEmpty()) {
            return Result.fail("请上传文件！");
        }
        try {
            StringBuilder pdfNames = new StringBuilder();
            StringBuilder pdfPaths = new StringBuilder();
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue; // 跳过空文件
                }

                // 生成唯一的文件名
                String originalFilename = file.getOriginalFilename();
                String fileName = StringUtils.cleanPath(originalFilename);
                if (pdfNames.length() > 0) {
                    pdfNames.append(";");
                    pdfPaths.append(";");
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                String currentTime = sdf.format(new Date());
                String departmentName = departmentMapper.getDepartmentNameById(departmentId);
                String fileN = currentTime + " " + departmentName + " " + "借调回函"+fileName;
                String rPath = secondmentMapper.getResponseZipPath(secondmentId);
                String departmentNameById = departmentMapper.getDepartmentNameById(departmentId);
                String filePath = rPath + "\\" + departmentNameById + " 借调材料";
                File newFile = new File(filePath);
                newFile.mkdirs();

                String cFilePath = filePath + "\\" + fileN;
                File pPath = new File(cFilePath);
                pPath.getParentFile().mkdirs();
                file.transferTo(pPath);
                pdfNames.append(fileN);
                pdfPaths.append(cFilePath);


            }

            // yyyy-MM-dd HH:mm:ss


            SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
            secondmentDistributeInfo.setDepartmentId(departmentId);
            secondmentDistributeInfo.setSecondmentId(secondmentId);
            secondmentDistributeInfo.setResponseFileName(pdfNames.toString());
            secondmentDistributeInfo.setResponseFilePath(pdfPaths.toString());
            //secondmentDistributeInfo.setResponseState("已回复");
            secondmentDistributeInfoMapper.saveResponseFile(secondmentDistributeInfo);
        } catch (Exception e) {
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }
    @Override
    public Result uploadTempFile(List<MultipartFile> files, Long secondmentId) {
        if (files == null || files.isEmpty()) {
            return Result.fail("请上传文件！");
        }
        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue; // 跳过空文件
                }

                // 生成唯一的文件名
                String originalFilename = file.getOriginalFilename();
                String fileName = StringUtils.cleanPath(originalFilename);
                String rPath = secondmentMapper.getResponseZipPath(secondmentId);
                String filePath = rPath + "\\" + "存档材料";
                File newFile = new File(filePath);
                if (!newFile.exists()) {
                    newFile.mkdirs(); // 如果文件夹不存在，则创建
                }

                String cFilePath = filePath + "\\" + fileName;
                File pPath = new File(cFilePath);
                pPath.getParentFile().mkdirs();
                file.transferTo(pPath);

            }

            // yyyy-MM-dd HH:mm:ss

        } catch (Exception e) {
            return Result.fail("文件上传失败！");
        }
        return Result.ok("文件上传成功！");
    }
    @Override
    public Result getResponseDepartment(ResponseDepartmentDTO responseDTO) {
        PageHelper.startPage(responseDTO.getPageNum(), responseDTO.getPageSize());
        List<SecondmentDistributeInfo> secondmentDistributeInfos = secondmentDistributeInfoMapper.getDidsBySecId(responseDTO.getSecondmentId());
        PageInfo<SecondmentDistributeInfo> pageInfo = new PageInfo<>(secondmentDistributeInfos);
        List<ResponseVO> responseVOList = new ArrayList<>();
        for (SecondmentDistributeInfo sc : secondmentDistributeInfos) {
            ResponseVO responseVO = new ResponseVO();
            String departmentName = departmentMapper.getDepartmentNameById(sc.getDepartmentId());
            responseVO.setDepartmentName(departmentName);
            responseVO.setResponseState(sc.getResponseState());
            responseVO.setDepartmentId(sc.getDepartmentId());
            responseVO.setSecondmentId(sc.getSecondmentId());
            responseVO.setResponseFileName(sc.getResponseFileName());
            responseVO.setConfirm(sc.getConfirm());
            responseVOList.add(responseVO);
        }
        ResResponseVO responseVO = new ResResponseVO();
        responseVO.setResponseVOList(responseVOList);
        responseVO.setTotal(pageInfo.getTotal());
        return Result.ok(responseVO);
    }
    //被借调部门进行上报操作
    @Override
    public Result changeResponseState(DidAndSidDTO didAndSidDTO) {
        Long departmentId = didAndSidDTO.getDepartmentId();
        Long secondmentId = didAndSidDTO.getSecondmentId();
        String departmentName = didAndSidDTO.getDepartmentName();
        // 每个人员的意见
        SecondmentInfoDTO secondmentInfoDTO = new SecondmentInfoDTO();
        secondmentInfoDTO.setSecondmentId(secondmentId);
        secondmentInfoDTO.setDepartmentName(departmentName);
        //查看该部门该借调事件是否有未处理的人员
        List<String> stateList = secondmentContentInfoMapper.getState(secondmentInfoDTO);
        if (stateList.size() > 0) {
            return Result.fail("还有意见未完成！");
        }

        // 回函
        SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
        secondmentDistributeInfo.setDepartmentId(departmentId);
        secondmentDistributeInfo.setSecondmentId(secondmentId);
        SecondmentDistributeInfo sd = secondmentDistributeInfoMapper.getResFile(secondmentDistributeInfo);
        //判断是否已上传回函
        if (sd.getResponseFilePath() == null) {
            return Result.fail("请上传回函！");
        }

        secondmentDistributeInfo.setResponseState("已上报");
        secondmentDistributeInfoMapper.changeResState(secondmentDistributeInfo);
        // 校验其他所有的东西是否完成
        return Result.ok("上报完成！");
    }


    @Override
    public Result getConfirmName(Long secondmentId,Long departmentId) {
        SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
        secondmentDistributeInfo.setDepartmentId(departmentId);
        secondmentDistributeInfo.setSecondmentId(secondmentId);
        SecondmentDistributeInfo secondmentDistributeInfo2 = secondmentDistributeInfoMapper.getResFile(secondmentDistributeInfo);
        String confirmName = secondmentDistributeInfo2.getConfirmName();
        return Result.ok(confirmName);
    }
    @Override
    public Result getResponseState(DidAndSidDTO didAndSidDTO) {
        Long departmentId = didAndSidDTO.getDepartmentId();
        Long secondmentId = didAndSidDTO.getSecondmentId();
        SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
        secondmentDistributeInfo.setDepartmentId(departmentId);
        secondmentDistributeInfo.setSecondmentId(secondmentId);
        Integer isResponse =  secondmentDistributeInfoMapper.getResponseState(secondmentDistributeInfo);
        if (isResponse > 0){
        return Result.ok(true);
        }
        return Result.ok(false);
    }
    @Override
    public void dowRes(Long departmentId, Long secondmentId, HttpServletResponse response) {
        SecondmentDistributeInfo secondmentDistributeInfo = new SecondmentDistributeInfo();
        secondmentDistributeInfo.setDepartmentId(departmentId);
        secondmentDistributeInfo.setSecondmentId(secondmentId);
        SecondmentDistributeInfo resFile = secondmentDistributeInfoMapper.getResFile(secondmentDistributeInfo);
        String responseFileName = resFile.getResponseFileName();
        String responseFilePath = resFile.getResponseFilePath();

        String[] pdfNames = responseFileName.split(";"); // 分割文件名
        String[] pdfPaths = responseFilePath.split(";"); // 分割文件路径
        if (pdfNames.length==1){
            FileUtils.download(responseFileName, responseFilePath, response);

        }else if(pdfNames.length>1){
            FileUtils.download(pdfNames, pdfPaths, response);

        }
    }
}
